/*
 * Copyright (c) 2009 Nathaniel Houghton <nathan@brainwerk.org>
 *                    Robert Kirchgessner <rkirchge@gmail.com>
 *
 * Permission to use, copy, modify, and distribute this software for
 * any purpose with or without fee is hereby granted, provided that
 * the above copyright notice and this permission notice appear in all
 * copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
 * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
 * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
 * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include <stdint.h>
#include <stdio.h>

#include <avr/eeprom.h>
#include <util/crc16.h>
#include <util/delay.h>

#include "config.h"
#include "util.h"
#include "lcd.h"
#include "usart.h"

int8_t
read_config(struct config *conf)
{
	eeprom_read_block(conf, 0, sizeof(*conf));

	if (valid_config(conf))
		return 0;

	return -1;
}

void
write_config(struct config *conf)
{
	uint16_t i;
	uint16_t crc;
	uint8_t *p;

	p = (uint8_t *) conf;

	crc = 0xffff;
	conf->crc = 0x0000;

	for (i = 0; i < sizeof(*conf); ++i) {
		crc = _crc16_update(crc, *p);
		++p;
	}

	conf->crc = crc;

	eeprom_write_block(conf, 0, sizeof(*conf));
}

uint8_t
valid_config(struct config *conf)
{
	uint8_t *p;
	uint16_t crc, orig_crc;
	int i;

	p = (uint8_t *) conf;
	orig_crc = conf->crc;

	conf->crc = 0;
	crc = 0xffff;
	for (i = 0; i < sizeof(*conf); ++i) {
		crc = _crc16_update(crc, *p);
		++p;
	}

	conf->crc = orig_crc;

	if (crc == orig_crc)
		return 1;
	
	return 0;
}
